package main

import (
	"fmt"
	"log"
	"net/http"
	"time"
)

//接收一个http.HandlerFunc ，返回一个http.HandlerFunc
//用于组装链
type Middleware func(http.HandlerFunc) http.HandlerFunc

//功能函数
//记录请求处理时长
func logging() Middleware {
	//返回middleware 对象
	return func(f http.HandlerFunc) http.HandlerFunc {
		//返回一个 http.HandlerFunc 对象
		return func(writer http.ResponseWriter, request *http.Request) {
			start := time.Now()
			defer func() {
				log.Println(request.URL.Path, time.Since(start))
			}()
			//调用业务函数
			f(writer, request)
		}
	}
}

//请求方法过滤器
func method(m string) Middleware {
	return func(handlerFunc http.HandlerFunc) http.HandlerFunc {
		return func(writer http.ResponseWriter, request *http.Request) {
			if request.Method != m {
				//方法不对，返回400
				http.Error(writer, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
			} else {
				//通过方法过滤
				handlerFunc(writer, request)
			}
		}
	}
}

//组装链函数
func handlerChain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {
	for _, middle := range middlewares {
		f = middle(f)
	}
	return f
}

//调用链
func main() {

	http.HandleFunc("/", handlerChain(Hello, method("GET"), logging()))
	http.ListenAndServe(":8989", nil)
}

//业务处理函数
func Hello(writer http.ResponseWriter, r *http.Request) {
	time.Sleep(1 * time.Second)
	fmt.Fprintf(writer, "hello wolrd")
}
